<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SignalR 连接调试测试</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.1/signalr.min.js"></script>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; }
        .log { background: #f0f0f0; padding: 10px; margin: 10px 0; height: 400px; overflow-y: auto; font-family: monospace; font-size: 12px; }
        .status { padding: 10px; margin: 10px 0; border: 1px solid #ddd; }
        .error { background: #ffe6e6; border-color: #ff0000; }
        .success { background: #e6ffe6; border-color: #00ff00; }
        .warning { background: #fff3e6; border-color: #ff9900; }
        .info { background: #e6f3ff; border-color: #0099ff; }
        button { margin: 5px; padding: 10px; }
        input { margin: 5px; padding: 5px; }
    </style>
</head>
<body>
    <h1>SignalR 连接调试测试</h1>
    
    <div id="connectionStatus" class="status">连接状态: 未初始化</div>
    
    <div>
        <button onclick="testConnection()">测试连接</button>
        <button onclick="testNegotiate()">测试协商</button>
        <button onclick="clearLog()">清空日志</button>
    </div>
    
    <div>
        <input type="text" id="username" value="TestUser" placeholder="用户名">
        <button onclick="testJoinUser()" id="joinBtn" disabled>测试加入用户</button>
    </div>
    
    <div>
        <h3>详细日志</h3>
        <div id="log" class="log"></div>
    </div>

    <script>
        let connection = null;
        let currentUserId = null;

        // 日志函数
        function log(message, type = 'info') {
            const logDiv = document.getElementById('log');
            const timestamp = new Date().toLocaleTimeString();
            const entry = document.createElement('div');
            entry.style.color = type === 'error' ? 'red' : 
                               type === 'success' ? 'green' : 
                               type === 'warning' ? 'orange' : 'black';
            entry.textContent = `[${timestamp}] ${message}`;
            logDiv.appendChild(entry);
            logDiv.scrollTop = logDiv.scrollHeight;
            console.log(`[${type.toUpperCase()}] ${message}`);
        }

        // 更新连接状态
        function updateStatus(status, type = 'info') {
            const statusDiv = document.getElementById('connectionStatus');
            statusDiv.textContent = `连接状态: ${status}`;
            statusDiv.className = `status ${type}`;
        }

        // 测试协商端点
        async function testNegotiate() {
            log('开始测试 SignalR 协商端点...', 'info');
            
            try {
                const response = await fetch('https://localhost:5001/signaling/negotiate?negotiateVersion=1', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'text/plain;charset=UTF-8'
                    }
                });
                
                if (response.ok) {
                    const data = await response.json();
                    log(`✅ 协商成功: ${JSON.stringify(data)}`, 'success');
                } else {
                    log(`❌ 协商失败: ${response.status} ${response.statusText}`, 'error');
                }
            } catch (err) {
                log(`❌ 协商请求失败: ${err.message}`, 'error');
            }
        }

        // 测试连接
        async function testConnection() {
            log('开始建立 SignalR 连接...', 'info');
            updateStatus('连接中...', 'warning');
            
            if (connection) {
                log('正在关闭现有连接...', 'info');
                await connection.stop();
                connection = null;
            }

            try {
                connection = new signalR.HubConnectionBuilder()
                    .withUrl('https://localhost:5001/signaling', {
                        skipNegotiation: false,
                        transport: signalR.HttpTransportType.WebSockets | signalR.HttpTransportType.ServerSentEvents | signalR.HttpTransportType.LongPolling
                    })
                    .withAutomaticReconnect([0, 2000, 10000, 30000])
                    .configureLogging(signalR.LogLevel.Debug)
                    .build();

                // 注册所有事件处理器
                connection.onreconnecting((error) => {
                    log(`🔄 正在重新连接: ${error ? error.message : '网络问题'}`, 'warning');
                    updateStatus('重新连接中...', 'warning');
                    document.getElementById('joinBtn').disabled = true;
                });

                connection.onreconnected((connectionId) => {
                    log(`✅ 重新连接成功: ${connectionId}`, 'success');
                    updateStatus('已重新连接', 'success');
                    document.getElementById('joinBtn').disabled = false;
                });

                connection.onclose((error) => {
                    log(`❌ 连接已关闭: ${error ? error.message : '正常关闭'}`, 'error');
                    updateStatus('连接已关闭', 'error');
                    document.getElementById('joinBtn').disabled = true;
                });

                // 注册 SignalR 事件
                connection.on('UserJoined', (data) => {
                    log(`✅ 收到 UserJoined 事件: ${JSON.stringify(data)}`, 'success');
                    if (data.userId || data.UserId) {
                        currentUserId = data.userId || data.UserId;
                        log(`✅ 用户ID已保存: ${currentUserId}`, 'success');
                    } else {
                        log(`⚠️ UserJoined 事件中没有找到 userId 或 UserId 字段`, 'warning');
                    }
                });

                connection.on('Error', (message) => {
                    log(`❌ 服务器错误: ${message}`, 'error');
                });

                // 开始连接
                log('正在启动连接...', 'info');
                await connection.start();
                
                log(`✅ SignalR 连接成功！连接ID: ${connection.connectionId}`, 'success');
                log(`📊 连接状态: ${getConnectionStateText(connection.state)}`, 'info');
                updateStatus('已连接', 'success');
                document.getElementById('joinBtn').disabled = false;
                
            } catch (err) {
                log(`❌ SignalR 连接失败: ${err.message}`, 'error');
                log(`❌ 错误详情: ${err.stack}`, 'error');
                updateStatus('连接失败', 'error');
            }
        }

        // 测试加入用户
        async function testJoinUser() {
            const username = document.getElementById('username').value;
            
            if (!connection || connection.state !== signalR.HubConnectionState.Connected) {
                log('❌ 连接未建立或状态不正确', 'error');
                return;
            }

            log(`🚀 开始测试 JoinUser: ${username}`, 'info');
            log(`📊 调用前状态: currentUserId = ${currentUserId}`, 'info');

            try {
                log('📡 正在调用 JoinUser...', 'info');
                await connection.invoke('JoinUser', username);
                log('✅ JoinUser 调用完成', 'success');
                
                // 检查结果
                setTimeout(() => {
                    if (currentUserId) {
                        log(`🎉 测试成功！用户ID: ${currentUserId}`, 'success');
                    } else {
                        log('❌ 测试失败！未收到 UserJoined 事件或 currentUserId 为空', 'error');
                    }
                }, 3000);
                
            } catch (err) {
                log(`❌ JoinUser 调用失败: ${err.message}`, 'error');
                log(`❌ 错误详情: ${err.stack}`, 'error');
            }
        }

        // 获取连接状态文本
        function getConnectionStateText(state) {
            switch (state) {
                case signalR.HubConnectionState.Disconnected: return '已断开';
                case signalR.HubConnectionState.Connecting: return '连接中';
                case signalR.HubConnectionState.Connected: return '已连接';
                case signalR.HubConnectionState.Disconnecting: return '断开中';
                case signalR.HubConnectionState.Reconnecting: return '重连中';
                default: return '未知状态';
            }
        }

        // 获取连接状态类型
        function getConnectionStateType(state) {
            switch (state) {
                case signalR.HubConnectionState.Connected: return 'success';
                case signalR.HubConnectionState.Connecting:
                case signalR.HubConnectionState.Reconnecting: return 'warning';
                case signalR.HubConnectionState.Disconnected:
                case signalR.HubConnectionState.Disconnecting: return 'error';
                default: return 'info';
            }
        }

        // 清空日志
        function clearLog() {
            document.getElementById('log').innerHTML = '';
        }

        // 页面加载时显示初始信息
        window.addEventListener('load', () => {
            log('页面已加载，SignalR 版本: ' + (typeof signalR !== 'undefined' ? '已加载' : '未加载'), 'info');
            log('当前URL: ' + window.location.href, 'info');
            log('用户代理: ' + navigator.userAgent, 'info');
            log('HTTPS状态: ' + (window.location.protocol === 'https:' ? '是' : '否'), 'info');
        });
    </script>
</body>
</html> 